package com.efounder.http;

import android.content.Context;
import android.util.Log;

import com.android.volley.DefaultRetryPolicy;
import com.android.volley.Request.Method;
import com.android.volley.RequestQueue;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.StringRequest;
import com.android.volley.toolbox.Volley;

import org.json.JSONObject;

import java.nio.charset.StandardCharsets;
import java.util.Map;

/**
 * http请求工具类（封装了volley）
 *
 * @author hudq
 * @deprecated 弃用，推荐使用JFCommonRequestManager
 */
public class EFHttpRequest {
    private static RequestQueue requestQueue;
    private String TAG = "VolleyRequest";
    private HttpRequestListener httpRequestListener;

    /**
     * only initialize once with Application context
     *
     * @param context
     */
    public static void init(Context context) {
        requestQueue = Volley.newRequestQueue(context);
    }

    @Deprecated
    public EFHttpRequest(Context context) {
        super();
    }

    public EFHttpRequest(String tag) {
        super();
        TAG = tag;
    }

    public EFHttpRequest(Context context, HttpRequestListener httpRequestListener) {
        super();
        this.httpRequestListener = httpRequestListener;
    }

    public void setHttpRequestListener(HttpRequestListener httpRequestListener) {
        this.httpRequestListener = httpRequestListener;
    }

    /**
     * http-get请求
     *
     * @param url
     */
    public void httpGet(String url) {
        httpGet(0, url);
    }

    /**
     * http-get请求
     *
     * @param requestCode 请求码，用于回调时，区分不同的请求
     * @param url
     */
    public void httpGet(final int requestCode, String url) {
        StringRequest request = new StringRequest(Method.GET, url, new Response.Listener<String>() {

            @Override
            public void onResponse(String response) {
                if (httpRequestListener != null) {
                    httpRequestListener.onRequestSuccess(requestCode, response);
                }
            }
        }, new Response.ErrorListener() {

            @Override
            public void onErrorResponse(VolleyError error) {
                if (httpRequestListener != null) {
                    String message = error.getMessage();
                    int resultCode = requestCode;
                    if (error.networkResponse != null) {
                        resultCode = error.networkResponse.statusCode;
                    }

                    httpRequestListener.onRequestFail(resultCode, message);
                }
            }
        });
        request.setRetryPolicy(new DefaultRetryPolicy(30000,
                0,
                DefaultRetryPolicy.DEFAULT_BACKOFF_MULT))
                .setTag(TAG);
        Log.d(TAG, "http get");
        requestQueue.add(request);
    }

    /**
     * http-get请求
     *
     * @param url
     */
    public void httpGet(String url, int timeout) {
        httpGet(0, url, timeout);
    }

    /**
     * http-get请求
     *
     * @param requestCode 请求码，用于回调时，区分不同的请求
     * @param url
     */
    public void httpGet(final int requestCode, String url, int timeout) {
        StringRequest request = new StringRequest(Method.GET, url, new Response.Listener<String>() {

            @Override
            public void onResponse(String response) {
                if (httpRequestListener != null) {
                    httpRequestListener.onRequestSuccess(requestCode, response);
                }
            }
        }, new Response.ErrorListener() {

            @Override
            public void onErrorResponse(VolleyError error) {
                if (httpRequestListener != null) {
                    String message = error.getMessage();
                    httpRequestListener.onRequestFail(requestCode, message);
                }
            }
        });
        request.setRetryPolicy(new DefaultRetryPolicy(timeout,
                DefaultRetryPolicy.DEFAULT_MAX_RETRIES,
                DefaultRetryPolicy.DEFAULT_BACKOFF_MULT))
                .setTag(TAG);
        Log.d(TAG, "http get");
        requestQueue.add(request);
    }

    /**
     * http-post请求
     *
     * @param url
     * @param params
     */
    public void httpPost(String url, Map<String, String> params) {
        httpPost(10, url, params);
    }

    /**
     * http-post请求
     *
     * @param requestCode 请求码，用于回调时，区分不同的请求
     * @param url
     * @param params
     */
    public void httpPost(final int requestCode, String url, final Map<String, String> params) {
        StringRequest request = new StringRequest(Method.POST, url, new Response.Listener<String>() {

            @Override
            public void onResponse(String response) {
                if (httpRequestListener != null) {
                    httpRequestListener.onRequestSuccess(requestCode, response);
                }
            }
        }, new Response.ErrorListener() {

            @Override
            public void onErrorResponse(VolleyError error) {
                if (httpRequestListener != null) {
                    String message = error.getMessage();
                    int resultCode = requestCode;
                    if (error.networkResponse != null) {
                        resultCode = error.networkResponse.statusCode;
                        String errorMsg = new String(error.networkResponse.data, StandardCharsets.UTF_8);
                        try {
                            JSONObject jsonObject = new JSONObject(errorMsg);
                            message = jsonObject.optString("error_description");
                        } catch (Exception e) {
                            message = error.getMessage();
                            e.printStackTrace();
                        }
                    }

                    httpRequestListener.onRequestFail(resultCode, message);
                }
            }
        }) {
            @Override
            protected Map<String, String> getParams() {
                return params;
            }
        };
        request.setRetryPolicy(new DefaultRetryPolicy(30000,
                0,
                DefaultRetryPolicy.DEFAULT_BACKOFF_MULT))
                .setTag(TAG);
        Log.d(TAG, "http post");
        requestQueue.add(request);
    }


    /**
     * 成功，失败的监听
     *
     * @author hudq
     */
    public interface HttpRequestListener {
        public void onRequestSuccess(int requestCode, String response);

        public void onRequestFail(int requestCode, String message);
    }

    /**
     * cancel request
     */
    public static void cancelRequest(String tag) {
        requestQueue.cancelAll(tag);
        Log.d(tag, "cancel request");
    }
}
